package com.dididoctor.patient.Activity.OneToOneChat;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dididoctor.patient.Activity.OneToOneChat.rec.RecorderButton;
import com.dididoctor.patient.Bean.MessageChatBean;
import com.dididoctor.patient.MV.EduActivity;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Ui.customlistview.OnRefreshListener;
import com.dididoctor.patient.Ui.customlistview.RefreshListView;
import com.dididoctor.patient.Utils.ABAppUtil;
import com.dididoctor.patient.Utils.ABFileUtil;
import com.dididoctor.patient.Utils.MyToast;
import com.dididoctor.patient.Utils.Util;
import com.dididoctor.patient.Utils.imageprocess.ABImageProcess;

import java.io.File;
import java.util.List;

/**
 * 项目名称：Psd
 * 类描述：一对一聊天
 * 创建人：张强
 * 创建时间：2015/7/20 17:39
 * 修改人：
 * 修改时间：2015/7/20 17:39
 * 修改备注：
 */

public class OneToOneChatActivity extends EduActivity implements OneToOneChatView {
    private Context mcontext;
    private EditText ev_content = null;
    private ImageButton but_more = null;
    private Button but_send_recorder = null;
    private Button but_send = null;
    private LinearLayout addMorePanel, but_addcamera, but_addpic, but_addnotice;
    private RefreshListView lv_forum;
    private OneToOneChatListAdapter_bak adapter = null;
    private View addRecordPanel = null;
    private RecorderButton but_record = null;
    private OneToOneChatPresenter presenter = null;
    private int page;
    private String capturePath = null;
    private TextView tv_title;
    //RequestCode
    private final static int TO_CAMEIA = 1001;
    private final static int TO_PHOTO = 1002;
    private final static int TO_ZOOM_PHOTO = 1004;
    private boolean isvoice = true;
    private String sessionId;
    private String sessionName;

    @Override
    public void setContentLayout() {
        setContentView(R.layout.activity_accompany_chat);
        sessionId = getIntent().getStringExtra("sessionId");
        sessionName = getIntent().getStringExtra("sessionName");

//        Intent intentred = new Intent();
//        intentred.setAction(ConstantValue.MY_Message_CHANGE);
//        intentred.putExtra("isShowRedCircle", false);
//        intentred.putExtra("friendId", FriendId);
//        OneToOneChatActivity.this.sendBroadcast(intentred);
    }


    @Override
    public void init() {
        this.mcontext = this;
        this.capturePath = ABFileUtil.getAppTmpPath() + "/TMP.jpg";
        setView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        this.presenter.stopReceiverChatMessage();//结束接收消息
    }

    public Bundle getBundle() {
        Bundle bundle = new Bundle();
        return bundle;
    }

    /**
     * 裁剪图片
     *
     * @param uri
     */
    private void startPhotoZoom(Uri uri) {
        ABImageProcess.compressImage2SD(new File(capturePath), capturePath, 712, 960, 85);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        //intent.putExtra("aspectX", 1);
        //intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        //intent.putExtra("outputX", 300);
        //intent.putExtra("outputY", 300);
        intent.putExtra("return-data", false);
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("output", Uri.fromFile(new File(capturePath))); //保存路径
        intent.putExtra("scale", true);
        startActivityForResult(intent, TO_ZOOM_PHOTO);
    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.but_more:
                ABAppUtil.hideSoftInput(this);
                if (addMorePanel.getVisibility() == View.VISIBLE) {
                    addMorePanel.setVisibility(View.GONE);
                } else {
                    addMorePanel.setVisibility(View.VISIBLE);
                    addRecordPanel.setVisibility(View.GONE);
                    but_send_recorder.setBackgroundResource(R.drawable.but_blue_selector);
                    ev_content.setVisibility(View.VISIBLE);
                }
                break;

            case R.id.but_send_recorder:
                ABAppUtil.hideSoftInput(this);
                addMorePanel.setVisibility(View.GONE);
                if (isvoice == true) {
                    addRecordPanel.setVisibility(View.VISIBLE);
                    but_send_recorder.setBackgroundResource(R.drawable.but_character_selector);
                    ev_content.setVisibility(View.INVISIBLE);
                    isvoice = false;
                } else {
                    addRecordPanel.setVisibility(View.GONE);
                    but_send_recorder.setBackgroundResource(R.drawable.but_blue_selector);
                    ev_content.setVisibility(View.VISIBLE);
                    isvoice = true;
                }
                break;
            case R.id.but_send:
                String text = this.ev_content.getText().toString();
                //String orderID;
                //tring studentID;
                //String userId;
                //String studentName;
                this.presenter.sendTextMsg(sessionId, sessionName, text);
                this.ev_content.setText("");
                break;
            case R.id.but_addcamera:
                this.capturePath = ABFileUtil.getAppTmpPath() + "/TMP.jpg";
                //Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
                //getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, );
                //getImageByCamera.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                //startActivityForResult(getImageByCamera, TO_CAMEIA);
                Intent takePictureIntent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(new File(capturePath)));
                startActivityForResult(takePictureIntent,
                        TO_CAMEIA);
                break;
            case R.id.but_addpic:
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, TO_PHOTO);
                break;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TO_CAMEIA && resultCode == RESULT_OK) {//来自系统相机的返回
            this.startPhotoZoom(Uri.fromFile(new File(capturePath)));
        } else if (requestCode == TO_PHOTO && resultCode == RESULT_OK && data != null) {//来自系统相册的返回
            Uri uri = data.getData();
            this.startPhotoZoom(uri);
        } else if (requestCode == TO_ZOOM_PHOTO && data != null) {//裁剪完成后
            this.presenter.sendImageFromUri(sessionId, sessionName, capturePath);
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    public void setView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(sessionName);
        this.ev_content = (EditText) findViewById(R.id.ev_content);
        this.but_send = (Button) findViewById(R.id.but_send);
        this.but_send_recorder = (Button) findViewById(R.id.but_send_recorder);
        this.but_more = (ImageButton) findViewById(R.id.but_more);
        this.addMorePanel = (LinearLayout) findViewById(R.id.addMorePanel);
        this.addRecordPanel = findViewById(R.id.addRecordPanel);
        this.but_record = (RecorderButton) findViewById(R.id.but_record);
        lv_forum = (RefreshListView) findViewById(R.id.lv_forum);
        lv_forum.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onPullDownRefresh() {
                page++;
                presenter.loadData(sessionId);
                lv_forum.onRefreshFinish();
            }

            @Override
            public void onLoadMoring() {
                //page++;
                //presenter.loadData(orderID, page);
                //presenter.startReceiverChatMessage();
                //lv_forum.onRefreshFinish();
            }

            @Override
            public void onScrollListener(AbsListView absListView, int i, int i1, int i2) {

            }
        });
        this.adapter = new OneToOneChatListAdapter_bak(this);
        lv_forum.setAdapter(this.adapter);
        this.but_send_recorder.setOnClickListener(this);
        this.but_send.setOnClickListener(this);

        ABAppUtil.hideSoftInput(this);
        //but_more.setFocusable(true);
        //but_more.setFocusableInTouchMode(true);
        //but_more.requestFocus(); // 初始不让EditText得焦点

        //but_more.requestFocusFromTouch();
        //but_more.clearFocus();
        this.but_more.setOnClickListener(this);

        //更多部分
        but_addcamera = (LinearLayout) findViewById(R.id.but_addcamera);
        but_addcamera.setOnClickListener(this);
        but_addpic = (LinearLayout) findViewById(R.id.but_addpic);
        but_addpic.setOnClickListener(this);
        but_addnotice = (LinearLayout) findViewById(R.id.but_addnotice);
        but_addnotice.setOnClickListener(this);

        //文字输入框内容变化时

        this.ev_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (Util.isEmpty(ev_content.getText().toString())) {
                    but_send_recorder.setVisibility(View.VISIBLE);
                    but_send.setVisibility(View.GONE);
                } else {
                    but_send_recorder.setVisibility(View.GONE);
                    but_send.setVisibility(View.VISIBLE);
                }
            }
        });

        //初始化语音发送按钮--事件监听
        this.but_record.setAudioFinshListener(new RecorderButton.AudioFinshListener() {
            @Override
            public void onFinish(float seconds, String filePath) {
                presenter.sendSecord((int) seconds, sessionId, sessionName, filePath);
            }
        });
        this.presenter = new OneToOneChatPresenter(OneToOneChatActivity.this, OneToOneChatActivity.this);
        page = 1;
        this.presenter.loadData(sessionId);
//        this.presenter.UpData(FriendId);
//        this.presenter.startReceiverChatMessage();
    }


    @Override
    public void fillData(List<MessageChatBean> chatMessageList) {
        this.adapter.setData(chatMessageList);
        if (lv_forum.getCount() > 0) {
            lv_forum.setSelection(lv_forum.getCount() - 1);
        }
    }

    @Override
    public void addData(List<MessageChatBean> chatMessageList) {
        if (chatMessageList.size() > 0) {
            this.adapter.addheaddata(chatMessageList);
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putInt("size", chatMessageList.size());
            msg.setData(data);
            mHandler.sendMessage(msg);
        } else {
            MyToast.DefaultmakeText(mcontext, "没有更多数据", 0);
        }
    }

    @Override
    public void append(MessageChatBean message) {
        adapter.addData(message);
        if (lv_forum.getCount() > 0) {
            lv_forum.setSelection(lv_forum.getCount() - 1);
        }
    }

    @Override
    public void sendTextOver() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (addMorePanel.getVisibility() == View.VISIBLE || addRecordPanel.getVisibility() == View.VISIBLE) {
                addMorePanel.setVisibility(View.GONE);
                addRecordPanel.setVisibility(View.GONE);
            } else {
                finish();
            }
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            return false;
        }
        return true;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (lv_forum.getCount() > 0) {
                Bundle bundle = msg.getData();
                int size = bundle.getInt("size");
                lv_forum.setSelection(size);
            }
        }
    };

}